package com.orange.common.net.ktx

import com.hjq.toast.Toaster
import rxhttp.tryAwait
import rxhttp.wrapper.cache.CacheMode
import rxhttp.wrapper.callback.IConverter
import rxhttp.wrapper.converter.GsonConverter
import rxhttp.wrapper.param.RxHttp
import rxhttp.wrapper.param.toAwaitResponse

/**
 * Created by Orange on 2022/11/17 21:33.
 * https://github.com/liujingxing/rxhttp/issues/327
 * https://github.com/liujingxing/rxhttp/issues/313
 */

// 封装层调用重载扩展函数
suspend inline fun <reified T : Any> callGet(
    path: String,
    params: Map<String, Any> = mapOf(),
    cacheMode: CacheMode = CacheMode.ONLY_NETWORK,
    converter: IConverter = GsonConverter.create(),
    noinline onCatch: ((Throwable) -> Unit) = { Toaster.show(it.msg) }
): T? {
    return RxHttp.get(path)
        .setConverter(converter)
        .addAll(params)
        .setCacheMode(cacheMode)
        .toAwaitResponse<T>()
        .tryAwait{
            if (!rxHttpGlobalCatch(it)) {
                onCatch.invoke(it)
            }
        }
}

/**
 *  复制一个一样的 用作post请求
 */
suspend inline fun <reified T : Any> callPost(
    path: String,
    params: Map<String, Any> = mapOf(),
    cacheMode: CacheMode = CacheMode.ONLY_NETWORK,
    converter: IConverter = GsonConverter.create(),
    noinline onCatch: ((Throwable) -> Unit) = { Toaster.show(it.msg) }
): T? {
    return RxHttp.postForm(path)
        .setConverter(converter)
        .addAll(params)
        .setCacheMode(cacheMode)
        .toAwaitResponse<T>()
        .tryAwait {
            if (!rxHttpGlobalCatch(it)) {
                onCatch.invoke(it)
            }
        }
}

/**
 * 全局异常处理
 */
var rxHttpGlobalCatch :(t: Throwable) -> Boolean = {false}